package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"time"
	"user-login1/models/cache"
	"user-login1/models/mysql"
	"user-login1/pkg"

	"user-login1/userrpc/internal/svc"
	"user-login1/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type WechatRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWechatRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WechatRegisterLogic {
	return &WechatRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 微信注册
func (l *WechatRegisterLogic) WechatRegister(in *userrpc.WechatRegisterRequest) (*userrpc.WechatRegisterResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result == "" {
		return nil, errors.New("您还未发送短信验证码")
	}
	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误")
	}
	user := &mysql.User{
		Mobile:     in.Mobile,
		Password:   pkg.Md5(in.Password),
		HeadImage:  in.HeadImage,
		NickName:   in.NickName,
		Address:    in.Address,
		WechatCode: fmt.Sprintf("we_%d%d", time.Now().Unix(), rand.Intn(100000)),
	}
	if err := user.FindWechatByMobile(mysql.DB, in.Mobile); err != nil {
		return nil, err
	}
	if user.ID != 0 {
		return nil, errors.New("用户已注册，请勿重复注册")
	}
	if err := user.UserCreate(mysql.DB); err != nil {
		return nil, errors.New("注册失败")
	}

	return &userrpc.WechatRegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
